import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';
import 'package:flutter_yres/pages/event/LoginEvent.dart';
import 'package:flutter_yres/tool/AppSaveInfoUtil.dart';
import 'package:dio/dio.dart';
import 'package:fake_wechat/fake_wechat.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter_yres/tool/application.dart';
import 'package:flutter_yres/tool/LoadingUtil.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_yres/model/banner_entity.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:cached_network_image/cached_network_image.dart';

class GoodSharePage extends StatefulWidget {
  Map goods_details;
  GoodSharePage({Key key, this.goods_details}) : super(key: key);

  @override
  _GoodSharePageState createState() => _GoodSharePageState();
}

class _GoodSharePageState extends State<GoodSharePage> {
  StreamSubscription<WechatSdkResp> _share;
  Wechat _wechat = Wechat()
    ..registerApp(appId: WX_APPID, universalLink: WECHAT_UNIVERSAL_LINK);
  bool isShow = true;
  GlobalKey rootWidgetKey = GlobalKey();
  String shareUrl = '';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: Text('分享',
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                color: Colors.black)),
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
        elevation: 0.5,
      ),
      body: RepaintBoundary(
        key: rootWidgetKey,
        child:Container(
          color: white,
          child:  SingleChildScrollView(
            child: Column(
          children: <Widget>[
            CachedNetworkImage(
              width: ScreenUtil.getInstance().setWidth(750),
              height: ScreenUtil.getInstance().setWidth(750),
              fit: BoxFit.fill,
              imageUrl: widget.goods_details['pict_url'],
              placeholder: (context, url) => Image.asset(
                'images/pic_default.png',
                fit: BoxFit.fill,
                width: ScreenUtil.getInstance().setWidth(750),
                height: ScreenUtil.getInstance().setWidth(750),
              ),
              errorWidget: (context, url, error) => Image.asset(
                'images/pic_default.png',
                fit: BoxFit.fill,
                width: ScreenUtil.getInstance().setWidth(750),
                height: ScreenUtil.getInstance().setWidth(750),
              ),
            ),
            //  Expanded(
            //         child:
            Row(
              children: <Widget>[
                Expanded(
                  child: Container(
                    margin:
                        EdgeInsets.all(ScreenUtil.getInstance().setWidth(10)),
                    alignment: Alignment.centerLeft,
                    child: RichText(
                      textAlign: TextAlign.left,
                      text: TextSpan(
                          style: TextStyle(color: Colors.red),
                          children: [
                            TextSpan(
                                text: '¥', style: TextStyle(fontSize: 12.0)),
                            TextSpan(
                                text: widget.goods_details['zk_final_price'] ==
                                        null
                                    ? '0'
                                    : widget.goods_details['zk_final_price']
                                        .toString(),
                                style: TextStyle(fontSize: 18.0)),
                            TextSpan(
                              text:
                                  widget.goods_details['reserve_price'] == null
                                      ? '0'
                                      : widget.goods_details['reserve_price']
                                          .toString(),
                              style: TextStyle(
                                  fontSize: 12.0,
                                  color: Colors.grey,
                                  decoration: TextDecoration.lineThrough,
                                  decorationColor: Colors.grey),
                            ),
                          ]),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    )),
                ),
                
                Container(
                    margin:
                        EdgeInsets.all(ScreenUtil.getInstance().setWidth(10)),
                    child: Row(
                      children: <Widget>[
                        Container(
                          width: ScreenUtil.getInstance().setWidth(40),
                          height: ScreenUtil.getInstance().setWidth(34),
                          decoration: BoxDecoration(
                            image: DecorationImage(
                              image: AssetImage(
                                  "images/item_youhuiquan_header.png"),
                              fit: BoxFit.cover,
                            ),
                          ),
                        ),
                        // Expanded(
                        // child:
                        Container(
                          width: ScreenUtil.getInstance().setWidth(70),
                          height: ScreenUtil.getInstance().setWidth(34),
                          decoration: BoxDecoration(
                            image: DecorationImage(
                              image: AssetImage(
                                  "images/item_youhuiquan_footer.png"),
                              fit: BoxFit.cover,
                            ),
                          ),
                          child: Center(
                              child: Text(
                            widget.goods_details['coupon_amount'] == null
                                ? '0元'
                                : widget.goods_details['coupon_amount']
                                        .toString() +
                                    '元',
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: ScreenUtil.getInstance().setSp(24)),
                          )),
                        ),
                        // )
                      ],
                    )),
              ],
              // ),
            ),

            Container(
              margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(10)),
              child: Row(
                children: <Widget>[
                  Expanded(
                    child: Container(
                        margin: EdgeInsets.all(
                            ScreenUtil.getInstance().setWidth(10)),
                        child: Column(
                          children: <Widget>[
                            Container(
                              alignment: Alignment.centerRight,
                              child: Text(
                                widget.goods_details['title'],
                                style: TextStyle(
                                    fontSize:
                                        ScreenUtil.getInstance().setSp(28)),
                              ),
                            ),
                            Container(
                                alignment: Alignment.centerRight,
                                child: Text(
                                  '长按图片，扫码领取优惠券',
                                  style: TextStyle(
                                      fontSize:
                                          ScreenUtil.getInstance().setSp(27),color: Colors.black54),
                                ))
                          ],
                        )),
                  ),
                  Container(
                    child: QrImage(
                      data: shareUrl,
                      version: QrVersions.auto,
                      size: ScreenUtil.getInstance().setHeight(150),
                      gapless: true,
                    ),
                  )
                ],
              ),
            )
          ],
        )),
      )),
      bottomNavigationBar: BottomAppBar(
          child: Row(
        children: <Widget>[
          Expanded(
              flex: 2,
              child: RaisedButton.icon(
                label: Text('分享'),
                icon: Image.asset("images/login_wx.png",width: ScreenUtil.getInstance().setWidth(50),),
                color: Colors.white,
                onPressed: () {
                  if (isShow) {
                    Fluttertoast.showToast(msg: "安装微信客户端后才能分享哦");
                    return;
                  }
                  showDialog(
                      context: context,
                      barrierDismissible: false,
                      builder: (_) {
                        return new NetLoadingDialog(
                          loadingText: "分享中...",
                          bgColor: Color.fromARGB(255, 0, 0, 0),
                          requestCallBack: null,
                          outsideDismiss: false,
                        );
                      });
                  _capturePng(WechatScene.SESSION);
                },
              )),
              
          // Expanded(
          //     flex: 2,
          //     child: RaisedButton.icon(
          //       label: Text('保存到相册'),
          //       icon: Icon(Icons.receipt),
          //       color: Colors.red,
          //       onPressed: () {},
          //     ))
        ],
      )),
    );
  }


  @override
  void initState() {
    print(widget.goods_details);
    checkWx();
    requestUrl();
    super.initState();
  }

  requestUrl() async {
    Map map = new Map();
    // map['sign_type'] = SignType.CHECK_VERSION;
    Response<String> response =
        await HttpUtil().post(Api.GetVersionUrl, data: {});
    Map userMap = json.decode(response.data);
    // print('=========版本检查=========');
    print(userMap);
    if (userMap['code'] == 0 && mounted) {
      setState(() {
        getString(UID).then((value) {
          shareUrl = userMap['data']['share_url'] +
              '/wap.php/Index/share/num_iid/' +
              widget.goods_details['num_iid'] +
              '/uid/' +
              value;
        });
      });
    }
  }

  checkWx() async {
    if (await _wechat.isWechatInstalled()) {
      _share = _wechat.shareMsgResp().listen(_listenShareMsg);
      setState(() {
        isShow = false;
      });
    } else {
      setState(() {
        isShow = true;
      });
    }
  }

  void _listenShareMsg(WechatSdkResp resp) {
    if (Platform.isIOS) {
      if (resp.errorCode == 0) {
        Fluttertoast.showToast(msg: "分享成功");
      } else {
        Fluttertoast.showToast(msg: "���享失败");
      }
    }
  }

  Widget buildImg(BuildContext context) {}

  _capturePng(plat) async {
    try {
      RenderRepaintBoundary boundary =
          rootWidgetKey.currentContext.findRenderObject();
      var image = await boundary.toImage(pixelRatio: 3.0);
      ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
      Uint8List pngBytes = byteData.buffer.asUint8List();
      _capturePath(pngBytes, byteData.buffer.asInt8List(), plat);
      Navigator.of(context).pop(1);
      return pngBytes;
    } catch (e) {
      Navigator.of(context).pop(1);
      print(e);
    }
    return null;
  }

  _capturePath(pngBytes, byteData, plat) async {
    String fileName = DateTime.now().millisecondsSinceEpoch.toString() + ".png";
    if (Platform.isAndroid) {
      PermissionStatus permission = await PermissionHandler()
          .checkPermissionStatus(PermissionGroup.storage);
      if (permission == PermissionStatus.granted) {
        Directory documentsDirectory = await getExternalStorageDirectory();
        String path = documentsDirectory.path;
        File file = File(path + "/$fileName");
        if (!file.existsSync()) {
          file.createSync();
          file.writeAsBytes(byteData);
        }
        if (plat != null) {
          await _wechat.shareImage(
            scene: plat,
            imageUri: Uri.file(file.path),
          );
        } else {
          Fluttertoast.showToast(msg: "保存成功");
        }
      } else {
        await PermissionHandler().requestPermissions([PermissionGroup.storage]);
      }
    } else {
      Directory documentsDirectory = await getApplicationDocumentsDirectory();
      String path = documentsDirectory.path;
      print(path);

      // final res = await _imageSaver.saveImage(
      // imageBytes: pngBytes, imageName: fileName, directoryName: path);
      File file = File(path + "/$fileName");
      if (!file.existsSync()) {
        file.createSync();
        file.writeAsBytes(byteData);
      }
      // if (res) {
      if (plat != null) {
        File file = File(path + "/$fileName");
        print(file.existsSync());
        await _wechat.shareImage(
          scene: plat,
          imageUri: Uri.file(file.path),
        );
      } else {
        Fluttertoast.showToast(msg: "保存成功");
      }
      // } else {
      //   Fluttertoast.showToast(msg: "失败");
      // }
    }
  }
}
